package com.lijia.ffmpeg4android.fragment;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.lijia.ffmpeg4android.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;

public class DatePickerFragment extends SherlockDialogFragment {
	public static final String EXTRA_DATE = "crime_date";
	private Date mDate;
	
	private void sendFragmentResult(int resultCode) {
		if (getTargetFragment() == null) {
			return;
		}
		
		Intent intent = new Intent();
		intent.putExtra(EXTRA_DATE, mDate);
		getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
	}

	public static DatePickerFragment newInstance(Date date) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_DATE, date);
		DatePickerFragment pdFragment = new DatePickerFragment();
		pdFragment.setArguments(args);
		return pdFragment;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
		Calendar cd = Calendar.getInstance();
		cd.setTime(mDate);
		int year = cd.get(Calendar.YEAR);
		int month = cd.get(Calendar.MONTH);
		int day = cd.get(Calendar.DAY_OF_MONTH);		
		
		DatePicker dp = (DatePicker)(getActivity().getLayoutInflater().inflate(R.layout.dialog_date, null));
		dp.init(year, month, day, new OnDateChangedListener() {
			public void onDateChanged(DatePicker dp, int year, int month, int day) {
				mDate = new GregorianCalendar(year,month,day).getTime();
				getArguments().putSerializable(EXTRA_DATE, mDate);
			}
		});
		return new AlertDialog.Builder(getActivity()).
				setView(dp).
				setTitle(R.string.date_pick_title).
				setPositiveButton(android.R.string.ok, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						sendFragmentResult(Activity.RESULT_OK);
					}
				}).
				create();
	}
	
}
